import {Vector as SourceVector, ImageCanvas} from 'ol/source';
import {Image as LayerImage, Vector as LayerVector} from 'ol/layer';
import {Circle, Fill, Style, Stroke, RegularShape} from 'ol/style';
import Feature from 'ol/Feature';
import {Point, Polygon} from 'ol/geom';
import {Select, DragBox} from 'ol/interaction'
import {platformModifierKeyOnly} from 'ol/events/condition'
import kriging from '@/utils/kriging';
import {message} from 'antd';
import 'ol-ext/control/Legend.css';
import Legend from 'ol-ext/control/Legend';

const Gkriging = {
  canvasLayer: null,
  legend: null,
  selectedFeatures: null,
  krigingImagecanvas: (selectValue, map, data, $cancelLoading) => {
    if (Gkriging.legend) {
      map.removeControl(Gkriging.legend);
    }
    if (Gkriging.selectedFeatures) {
      Gkriging.selectedFeatures.clear();
    }
    var layers = map.getLayers();
    layers.forEach(key => {
      if (key != undefined && key.values_.id != 'base') {
        map.removeLayer(key);
      }
    });
    let params = {
      krigingModel: 'exponential',//model可选'exponential','gaussian','spherical'
      krigingSigma2: 0.2,
      krigingAlpha: 100,
      canvasAlpha: 0.75,//canvas图层透明度
      colors:  [
        "#006837",
        "#1a9850",
        "#66bd63",
        "#a6d96a",
        "#fee08b",
        "#fdae61",
        "#f46d43",
        "#d73027",
        "#a50026"]
      // colors: ["#00A600", "#01A600", "#03A700", "#04A700", "#05A800", "#07A800", "#08A900", "#09A900", "#0BAA00", "#0CAA00", "#0DAB00", "#0FAB00", "#10AC00", "#12AC00", "#13AD00", "#14AD00", "#16AE00", "#17AE00", "#19AF00", "#1AAF00", "#1CB000", "#1DB000", "#1FB100", "#20B100", "#22B200", "#23B200", "#25B300", "#26B300", "#28B400", "#29B400", "#2BB500", "#2CB500", "#2EB600", "#2FB600", "#31B700", "#33B700", "#34B800", "#36B800", "#37B900", "#39B900", "#3BBA00", "#3CBA00", "#3EBB00", "#3FBB00", "#41BC00", "#43BC00", "#44BD00", "#46BD00", "#48BE00", "#49BE00", "#4BBF00", "#4DBF00", "#4FC000", "#50C000", "#52C100", "#54C100", "#55C200", "#57C200", "#59C300", "#5BC300", "#5DC400", "#5EC400", "#60C500", "#62C500", "#64C600", "#66C600", "#67C700", "#69C700", "#6BC800", "#6DC800", "#6FC900", "#71C900", "#72CA00", "#74CA00", "#76CB00", "#78CB00", "#7ACC00", "#7CCC00", "#7ECD00", "#80CD00", "#82CE00", "#84CE00", "#86CF00", "#88CF00", "#8AD000", "#8BD000", "#8DD100", "#8FD100", "#91D200", "#93D200", "#95D300", "#97D300", "#9AD400", "#9CD400", "#9ED500", "#A0D500", "#A2D600", "#A4D600", "#A6D700", "#A8D700", "#AAD800", "#ACD800", "#AED900", "#B0D900", "#B2DA00", "#B5DA00", "#B7DB00", "#B9DB00", "#BBDC00", "#BDDC00", "#BFDD00", "#C2DD00", "#C4DE00", "#C6DE00", "#C8DF00", "#CADF00", "#CDE000", "#CFE000", "#D1E100", "#D3E100", "#D6E200", "#D8E200", "#DAE300", "#DCE300", "#DFE400", "#E1E400", "#E3E500", "#E6E600", "#E6E402", "#E6E204", "#E6E105", "#E6DF07", "#E6DD09", "#E6DC0B", "#E6DA0D", "#E6D90E", "#E6D710", "#E6D612", "#E7D414", "#E7D316", "#E7D217", "#E7D019", "#E7CF1B", "#E7CE1D", "#E7CD1F", "#E7CB21", "#E7CA22", "#E7C924", "#E8C826", "#E8C728", "#E8C62A", "#E8C52B", "#E8C42D", "#E8C32F", "#E8C231", "#E8C133", "#E8C035", "#E8BF36", "#E9BE38", "#E9BD3A", "#E9BC3C", "#E9BB3E", "#E9BB40", "#E9BA42", "#E9B943", "#E9B945", "#E9B847", "#E9B749", "#EAB74B", "#EAB64D", "#EAB64F", "#EAB550", "#EAB552", "#EAB454", "#EAB456", "#EAB358", "#EAB35A", "#EAB35C", "#EBB25D", "#EBB25F", "#EBB261", "#EBB263", "#EBB165", "#EBB167", "#EBB169", "#EBB16B", "#EBB16C", "#EBB16E", "#ECB170", "#ECB172", "#ECB174", "#ECB176", "#ECB178", "#ECB17A", "#ECB17C", "#ECB17E", "#ECB27F", "#ECB281", "#EDB283", "#EDB285", "#EDB387", "#EDB389", "#EDB38B", "#EDB48D", "#EDB48F", "#EDB591", "#EDB593", "#EDB694", "#EEB696", "#EEB798", "#EEB89A", "#EEB89C", "#EEB99E", "#EEBAA0", "#EEBAA2", "#EEBBA4", "#EEBCA6", "#EEBDA8", "#EFBEAA", "#EFBEAC", "#EFBFAD", "#EFC0AF", "#EFC1B1", "#EFC2B3", "#EFC3B5", "#EFC4B7", "#EFC5B9", "#EFC7BB", "#F0C8BD", "#F0C9BF", "#F0CAC1", "#F0CBC3", "#F0CDC5", "#F0CEC7", "#F0CFC9", "#F0D1CB", "#F0D2CD", "#F0D3CF", "#F1D5D1", "#F1D6D3", "#F1D8D5", "#F1D9D7", "#F1DBD8", "#F1DDDA", "#F1DEDC", "#F1E0DE", "#F1E2E0", "#F1E3E2", "#F2E5E4", "#F2E7E6", "#F2E9E8", "#F2EBEA", "#F2ECEC", "#F2EEEE", "#F2F0F0", "#F2F2F2"]
    };

    let WFSVectorSource = new SourceVector();
    let WFSVectorLayer = new LayerVector(
      {
        source: WFSVectorSource,
        zIndex: 1000
      });
    map.addLayer(WFSVectorLayer);
    //创建要素
    var selectCode = selectValue.split(',')[0]
    for (let i = 0; i < data.length; i++) {
      let feature = new Feature({
        geometry: new Point(data[i].getGeometry().getCoordinates()),
        value: data[i].getProperties()[selectCode] ? data[i].getProperties()[selectCode] : 0
      })
      //"#2a5eff"
      feature.setStyle(new Style({
        image: new Circle({
          radius: 6,
          fill: new Fill({color: '#ffff00'})
        })
      }));
      WFSVectorSource.addFeature(feature);
    }
    //添加选择和框选控件，按住Ctrl/⌘键，使用鼠标框选采样点
    let select = new Select();
    map.addInteraction(select);
    let dragBox = new DragBox({
      condition: platformModifierKeyOnly
    });
    map.addInteraction(dragBox);

    //设置框选事件
    Gkriging.selectedFeatures = select.getFeatures();
    dragBox.on('boxend', () => {
      let extent = dragBox.getGeometry().getExtent();
      WFSVectorSource.forEachFeatureIntersectingExtent(extent, (feature) => {
        Gkriging.selectedFeatures.push(feature);
      });
      drawKriging(extent);
    });
    dragBox.on('boxstart', () => {
      Gkriging.selectedFeatures.clear();
    });
    //定义裁剪边界
    let coord = [[
      [115.57648498, 37.63931973], [115.57837283, 37.62437429], [115.58230584, 37.61760951], [115.59850984, 37.61446310], [115.59379023, 37.61100205], [115.57978871, 37.59275288], [115.57821551, 37.58677471], [115.57569838, 37.58472954], [115.57255197, 37.58787595], [115.57585570, 37.59432609], [115.57223733, 37.59715786], [115.56783236, 37.58771863], [115.56987752, 37.55672650], [115.59850984, 37.56065952], [115.61188208, 37.58661739], [115.61078084, 37.60360799], [115.62399575, 37.60077623], [115.62887269, 37.60832761], [115.62981661, 37.62421697], [115.65483056, 37.66134459], [115.57648498, 37.63931973]
    ]];
    let clipgeom = new Polygon(coord);
    //绘制kriging插值图
    let drawKriging = function (extent) {
      let values = [], lngs = [], lats = [];
      WFSVectorSource.forEachFeature(function (feature) {
        values.push(feature.getProperties().value);
        lngs.push(feature.getGeometry().getCoordinates()[0]);
        lats.push(feature.getGeometry().getCoordinates()[1]);
      })
      console.log(values.length)
      if (values.length > 3) {
        let letiogram = kriging.train(values, lngs, lats,
          params.krigingModel, params.krigingSigma2, params.krigingAlpha);
        let ex = clipgeom.getExtent();
        let grid = kriging.grid(coord, letiogram, (ex[2] - ex[0]) / 200);
        //移除已有图层
        if (Gkriging.canvasLayer !== null) {
          map.removeLayer(Gkriging.canvasLayer);
        }
        //创建新图层
        Gkriging.canvasLayer = new LayerImage({
          source: new ImageCanvas({
            canvasFunction: (extent, resolution, pixelRatio, size, projection) => {
              let canvas = document.createElement('canvas');
              canvas.width = size[0];
              canvas.height = size[1];
              canvas.style.display = 'block';
              //设置canvas透明度
              canvas.getContext('2d').globalAlpha = params.canvasAlpha;
              //使用分层设色渲染
              kriging.plot(canvas, grid,
                [extent[0], extent[2]], [extent[1], extent[3]], params.colors);
              return canvas;
            },
            projection: 'EPSG:4326'
          })
        })
        //向map添加图层
        map.addLayer(Gkriging.canvasLayer);

        // Define a new legend
        Gkriging.legend = new Legend({
          title: '色值分段',
          style: '',
          collapsed: false
        });
        map.addControl(Gkriging.legend);
        if (grid.zlim!=null && grid.zlim.length == 2) {
          var mean = Number(grid.zlim[0] + grid.zlim[1]) / params.colors.length;
          for (let i = 0; i < params.colors.length; i++) {
            Gkriging.legend.addRow({
              title: Number(grid.zlim[0] + mean * i).toFixed(2) + ' - ' + Number(grid.zlim[0] + mean * (i + 1)).toFixed(2),
              typeGeom: 'Point',
              style: new Style({
                image: new RegularShape({
                  points: 32,
                  rotation: 45,
                  radius: 10,
                  stroke: new Stroke({ color:  params.colors[i], width: 1.5 }),
                  fill: new Fill({ color:  params.colors[i]})
                })
              })
            });
          }
        }
      } else {
        message.info("有效样点个数不足，无法插值", 5);
      }
    }
    //首次加载，自动渲染一次差值图
    let extent = clipgeom.getExtent();
    drawKriging(extent);
    $cancelLoading;
  }
}
export default Gkriging;
